<template>
  <view class="page">
    <u-form
      :model="pageForm"
      ref="formRef"
      label-position="top"
      :border-bottom="false"
      :label-style="labelStyle"
      :placeholder-style="placeholderStyle"
    >
      <u-form-item label="店铺名称" prop="shopName"
        ><u-input v-model="pageForm.shopName" border :border-color="borderColor" placeholder="请输入名称"
      /></u-form-item>
      <u-form-item label="店铺类型" prop="shopType">
        <u-input
          v-model="shopTypeDisplayValue"
          type="select"
          @click="showShopTypeSelect = true"
          :select-open="showShopTypeSelect"
          :border="true"
          :border-color="borderColor"
          placeholder="请选择店铺类型"
        />
        <u-select
          v-model="showShopTypeSelect"
          mode="single-column"
          :list="shopTypeOptions"
          label-name="label"
          value-name="value"
          @confirm="shopTypeSelect"
          :defaultValue="[currentShopTypeIndex]"
        >
        </u-select>
      </u-form-item>

      <u-form-item label="所属品牌" prop="brandId" v-if="fromType != 'form'">
        <u-input
          v-model="brandIdDisplayValue"
          type="select"
          @click="showBrandIdSelect = true"
          :select-open="showBrandIdSelect"
          :border="true"
          :border-color="borderColor"
          placeholder="请选择所属品牌"
        />
        <u-select
          v-model="showBrandIdSelect"
          mode="single-column"
          :list="brandIdOptions"
          label-name="label"
          value-name="value"
          @confirm="brandIdSelect"
          :defaultValue="[currentBrandIdIndex]"
        >
        </u-select>
      </u-form-item>
      <!-- <u-form-item label="店铺地址" prop="brandName2">
        <u-picker
          v-model="showRegionPicker"
          mode="region"
          @confirm="pickerConfirm"
          :default-region="defaultRegion"
        ></u-picker>
        <view
          class="picker_display"
          :class="pickerDisPlayValue ? '' : 'placeholder'"
          @click="showRegionPicker = true"
          >{{ pickerDisPlayValue ? pickerDisPlayValue : '请选择省市区' }}</view
        >
      </u-form-item> -->

      <u-form-item label="店铺详细地址" prop="shopAddress"
        ><u-input v-model="pageForm.shopAddress" border :border-color="borderColor" placeholder="请输入详细地址"
      /></u-form-item>

      <u-form-item label="行业类型" prop="industryType">
        <u-input
          v-model="industryTypeDisplayValue"
          type="select"
          @click="showIndustryTypeSelect = true"
          :select-open="showIndustryTypeSelect"
          :border="true"
          :border-color="borderColor"
          placeholder="请选择行业类型"
        />
        <u-select
          v-model="showIndustryTypeSelect"
          mode="single-column"
          :list="industryTypeOptions"
          label-name="label"
          value-name="value"
          @confirm="industryTypeSelect"
          :defaultValue="[currentIndustryTypeIndex]"
        >
        </u-select>
      </u-form-item>

      <u-form-item label="人均消费" prop="avgPrice"
        ><u-input v-model="pageForm.avgPrice" border :border-color="borderColor" placeholder="请输入人均消费(元)" />
      </u-form-item>
      <u-form-item label="营业时间" prop="businessTime"
        ><u-input v-model="pageForm.businessTime" border :border-color="borderColor" placeholder="请输入营业时间" />
      </u-form-item>

      <u-form-item label="品牌备用核销账号（仅支持手机号）">
        <view class="backup_phones" v-for="(item, index) in pageForm.standbyVerfiyAccount">
          <u-input
            v-model="item.value"
            border
            :border-color="borderColor"
            placeholder="请输入手机号"
            :custom-style="customStyle"
          />
          <image
            v-if="index == pageForm.standbyVerfiyAccount.length - 1"
            class="add_btn"
            src="/static/form/add2.png"
            mode="aspectFill"
            @click="handlePhoneAdd"
          ></image>
          <image
            v-else
            class="add_btn"
            src="/static/form/minus.png"
            mode="aspectFill"
            @click="handlePhoneMinus(index)"
          ></image>
        </view>
      </u-form-item>

      <u-form-item label="店铺评分" prop="shopScore">
        <u-rate
          :count="5"
          :min-count="1"
          v-model="pageForm.shopScore"
          :gutter="16"
          :size="40"
          active-color="#ffac41"
        ></u-rate>
      </u-form-item>

      <u-form-item label="店铺图片(16：9)">
        <u-upload
          ref="upload1"
          :auto-upload="false"
          max-count="3"
          :action="UPLOAD_URL"
          :file-list="fileList1"
          @on-list-change="handleListChange"
          :customBtn="true"
          width="145rpx"
          height="145rpx"
          :header="uploadHeader"
          @on-uploaded="onUploaded1"
        >
          <template v-slot:addBtn>
            <image class="upload_hover_bg" src="/static/upload_hover_bg.png" mode="aspectFill"></image>
          </template>
        </u-upload>
      </u-form-item>

      <!-- 营业执照上传  -->
      <view class="upload_box">
        <u-upload
          width="100%"
          height="calc((100vw - 80rpx) * 0.4414)"
          ref="upload2"
          :auto-upload="false"
          max-count="1"
          :action="UPLOAD_URL"
          :file-list="fileList2"
          :customBtn="true"
          :header="uploadHeader"
          @on-uploaded="onUploaded2"
        >
          <template v-slot:addBtn>
            <view class="hover_box">
              <image class="img" src="/static/form/add.png" mode="aspectFill"></image>
            </view>
          </template>
        </u-upload>
      </view>

      <view class="upload_tip">请上传营业执照/品牌授权书</view>
    </u-form>

    <view class="create_btn" @click="createGoods">创建商品</view>
    <div
      class="created_list"
      v-if="formStore?.currentGoodsList(fromType) && formStore.currentGoodsList(fromType).length > 0"
    >
      <div class="item" v-for="item in formStore.currentGoodsList(fromType)">{{ item.goodsName }}</div>
    </div>

    <view class="submit" @click="submit">{{ fromType == 'form' ? '确定' : '提交审核' }}</view>
    <view class="safe_area" :style="{ height: '80rpx' }"></view>
  </view>
</template>

<script setup>
  import { ref, reactive, computed } from 'vue';
  import { onShow, onLoad } from '@dcloudio/uni-app';
  import { UPLOAD_URL } from '../../config/config';
  import { useFormStore } from '../../store/form';
  import { useUserStore } from '../../store/user';
  import { queryAllBrand, addShop } from '../../apis/pages';

  const userStore = useUserStore();
  const formStore = useFormStore();

  const fromType = ref('home');

  const borderColor = '#747474';

  const showRegionPicker = ref(false);
  const pickerDisPlayValue = ref('');

  const defaultRegion = ref([]);

  const customStyle = {
    width: 'calc(100vw - 200rpx)',
  };

  const pageForm = reactive({
    shopName: '', // 店铺名
    shopType: '', // 店铺类型
    // shopAddress: '江苏省南京市玄武区恒嘉路中电颐和家园', // 店铺地址
    shopAddress: '江苏省南京市玄武区恒嘉路中电颐和家园', // 店铺地址
    industryType: '', // 行业类型
    avgPrice: '', // 平均消费金额
    businessTime: '', // 营业时间
    standbyVerfiyAccount: [
      {
        value: '',
      },
    ],
    shopScore: 5, // 评分
  });

  const uploadForm = reactive({
    shopImage: '', //logo图
    shopInfoImage: '', //品牌图
  });

  // 三个上传完成标志
  const uploadStatus = reactive({
    shopImageUploaded: false,
    shopInfoImageUploaded: false,
  });

  function resetUploadStatus() {
    uploadStatus.shopImageUploaded = false;
    uploadStatus.shopInfoImageUploaded = false;
  }

  const isSubmit = ref(false);

  // 上传相关
  const upload1 = ref();
  const upload2 = ref();
  const uploadHeader = {
    authorization: 'Bearer ' + userStore.token,
  };

  // 图片1 是否上传了
  const isImgUploaded1 = ref(false);
  const fileList1 = ref([]);

  const fileList2 = ref([]);

  // form 样式相关

  const labelStyle = {
    'font-weight': 600,
    'font-size': '30rpx',
    color: '#1E2737',
    // width: '100%',
  };

  const placeholderStyle = {
    'font-weight': 500,
    'font-size': '26rpx',
    color: '#989898',
  };

  const verifyLabelStyle = {
    'font-weight': 500,
    'font-size': '26rpx',
    color: '#989898',
  };

  // 归属select
  const showShopTypeSelect = ref(false);
  const shopTypeDisplayValue = ref('');
  const currentShopTypeIndex = ref(0);
  const shopTypeOptions = [
    {
      label: '独立门店',
      value: '1',
    },
    {
      label: '直营连锁店',
      value: '2',
    },
    {
      label: '加盟连锁店',
      value: '3',
    },
  ];

  const showBrandIdSelect = ref(false);
  const brandIdDisplayValue = ref('');
  const currentBrandIdIndex = ref(0);
  const brandIdOptions = ref([]);

  // 行业类型
  const showIndustryTypeSelect = ref(false);
  const industryTypeDisplayValue = ref('');
  const currentIndustryTypeIndex = ref(0);
  const industryTypeOptions = [
    {
      label: '餐饮美食',
      value: '1',
    },
    {
      label: '休闲娱乐',
      value: '2',
    },
    {
      label: '亲子乐园',
      value: '3',
    },
  ];

  onLoad((options) => {
    console.log(options, 'options');
    // 从上级表单创建
    if (options.from) {
      fromType.value = options.from;
    }

    console.log('onLoad');
    getBrandOptions();
  });

  function getBrandOptions() {
    queryAllBrand({
      merchantId: uni.getStorageSync('merchantId'),
    }).then((res) => {
      console.log(res, 'brands res >>>>>>');
      brandIdOptions.value = res.data.map((item) => {
        return {
          label: item.brandName,
          value: item.id,
        };
      });
    });
  }

  function shopTypeSelect(e) {
    pageForm.shopType = e[0].value;
    showShopTypeSelect.value = false;
    currentShopTypeIndex.value = e[0].index;
    shopTypeDisplayValue.value = e[0].label;
  }

  function brandIdSelect(e) {
    pageForm.brandId = e[0].value;
    showBrandIdSelect.value = false;
    currentBrandIdIndex.value = e[0].index;
    brandIdDisplayValue.value = e[0].label;
  }

  function industryTypeSelect(e) {
    pageForm.industryType = e[0].value;
    showIndustryTypeSelect.value = false;
    currentIndustryTypeIndex.value = e[0].index;
    industryTypeDisplayValue.value = e[0].label;
  }

  // 上传组件本地图片列表变化
  function handleListChange(n) {
    // upload1.value.lists 是获取组件内部展示图片列表
    if (upload1.value.lists.length > 0) {
      isImgUploaded1.value = true;
    } else {
      isImgUploaded1.value = false;
    }
  }

  // 增加备用手机号(4)
  function handlePhoneAdd() {
    if (pageForm.standbyVerfiyAccount.length == 4) {
      uni.showToast({
        title: '最多添加4个',
        icon: 'none',
      });
    } else {
      pageForm.standbyVerfiyAccount.push({
        value: '',
      });
    }
  }

  // 减少备用手机号
  function handlePhoneMinus(index) {
    pageForm.standbyVerfiyAccount.splice(index, 1);
  }

  const isCreateNew = ref(false);
  function createGoods() {
    isCreateNew.value = true;
    submit();
  }

  function pickerConfirm(e) {
    console.log(e, 'eeee >>>>');
    pickerDisPlayValue.value = e.province.name + '/' + e.city.name + '/' + e.area.name;
    defaultRegion.value = [e.province.name, e.city.name, e.area.name];
  }

  function onUploaded1(list) {
    // uploadForm.shopImage = list[0].response.data;
    uploadForm.shopImage = list
      .map((item) => {
        return item.response.data;
      })
      .join(',');
    uploadStatus.shopImageUploaded = true;
    checkAllUploaded();
  }

  function onUploaded2(list) {
    uploadForm.shopInfoImage = list[0].response.data;
    uploadStatus.shopInfoImageUploaded = true;
    checkAllUploaded();
  }

  // 检查是否全部上传完
  function checkAllUploaded() {
    const allUploaded = Object.values(uploadStatus).every((status) => status);

    if (allUploaded) {
      isSubmit.value = false;
      resetUploadStatus();
      uni.hideLoading();
      mergeForm();
    }
  }

  // 合并表单
  function mergeForm() {
    console.log('所有图片上传成功，可以合并数据了');

    console.log(fromType.value, 'fromType >>>');

    console.log((uploadForm, 'uploadForm >>>'));

    // 更新页面数据到对应商铺
    formStore.updateShopById(
      formStore.currentShopId,
      {
        ...pageForm,
        ...uploadForm,
        standbyVerfiyAccount: pageForm.standbyVerfiyAccount.map((item) => item.value).join(','),
        // goodsList: [],
      },
      fromType.value
    );

    // * 创建商品
    if (isCreateNew.value) {
      formStore.addGoodsByShopId(fromType.value);
      isCreateNew.value = false;
      uni.navigateTo({
        url: '/pagesB/goods/index?from=form',
      });
    } else {
      // * 按钮提交
      if (fromType.value == 'form') {
        // formStore.currentShopId = -1;
        uni.navigateBack();
      } else {
        // * 审核按钮(首页进入提交) 走店铺提交接口
        console.log('提交数据 >>>', formStore.shopForm);
        formStore.shopForm.merchantId = uni.getStorageSync('merchantId');
        addShop(formStore.shopForm).then((res) => {
          console.log(res, 'res >>>');
          if (res.code == 200) {
            uni.reLaunch({ url: '/pagesB/register/finish' });
          }
        });
      }
    }
  }

  function submit() {
    if (isSubmit.value) return;
    console.log(pageForm, 'pageForm >>>');

    if (upload1.value.lists.length && upload2.value.lists.length) {
      isSubmit.value = true;
      uni.showLoading({
        title: '提交中...',
        mask: true,
      });
      upload1.value.upload();
      upload2.value.upload();
    } else {
      mergeForm();
    }
  }
</script>

<style scoped lang="scss">
  // /deep/ .u-form-item {
  //   padding-bottom: 0 !important;
  // }

  .page {
    width: 100vw;
    min-height: 100vh;
    padding: 40rpx;
    box-sizing: border-box;
    font-size: 28rpx;
    background-color: #f5f5f5;
  }

  .upload_hover_bg {
    width: 145rpx;
    height: 145rpx;
    vertical-align: middle;
  }

  .content {
    background-color: #fff;
    padding: 20rpx;
    border-radius: 16rpx;
    box-sizing: border-box;
    margin-bottom: 30rpx;
  }

  .label_title {
    font-weight: 600;
    font-size: 30rpx;
    color: #1e2737;
    margin-bottom: 30rpx;
  }

  .verify_form {
    padding: 0 20rpx;
  }

  .upload_box {
    margin-bottom: 20rpx;
  }

  .hover_box {
    display: flex;
    align-items: center;
    justify-content: center;
    width: calc(100vw - 80rpx);
    height: calc((100vw - 80rpx) * 0.4414);
    background-color: #e5e5e5;
    border-radius: 20rpx;
    overflow: hidden;

    .img {
      width: 102rpx;
      height: 102rpx;
    }
  }

  .upload_tip {
    font-weight: 500;
    font-size: 26rpx;
    color: #989898;
    text-align: center;
    margin-bottom: 40rpx;
  }

  .create_btn {
    width: 188rpx;
    height: 67rpx;
    border: 2rpx solid #4287f6;
    text-align: center;
    line-height: 67rpx;
    box-sizing: border-box;
    font-weight: 500;
    font-size: 27rpx;
    color: #4287f6;
    border-radius: 40rpx;
    margin-bottom: 32rpx;
  }

  .created_list {
    margin-bottom: 40rpx;

    .item {
      font-weight: 600;
      font-size: 30rpx;
      color: #1e2737;
      border-bottom: 2rpx solid #e5e5e5;
      padding-left: 4rpx;
      padding-bottom: 12rpx;
      margin-bottom: 16rpx;
    }
  }

  .submit {
    width: 537rpx;
    height: 83rpx;
    background: #016bec;
    border-radius: 10rpx;

    font-weight: 500;
    font-size: 30rpx;
    color: #ffffff;

    text-align: center;
    line-height: 83rpx;
    margin: 0 auto;
  }

  .backup_phones {
    display: flex;
    align-items: center;
    margin-bottom: 10rpx;

    .add_btn {
      width: 64rpx;
      min-width: 64rpx;
      height: 64rpx;
      margin-left: 12rpx;
    }
  }

  .picker_display {
    width: 100%;
    max-width: 670rpx;
    height: 75rpx;
    border: 2rpx solid #747474;
    font-size: 28rpx;
    color: #303133;
    border-radius: 8rpx;
    padding: 0 20rpx;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;

    &.placeholder {
      color: #c0c4cc;
    }
  }
</style>
